import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import bcrypt from 'bcrypt';

export async function POST(req: NextRequest) {
  const { username, password } = await req.json();

  if (!username || !password) {
    return NextResponse.json({ error: '用户名和密码不能为空' }, { status: 400 });
  }

  const user = await prisma.user.findUnique({ where: { username } });
  if (!user) {
    return NextResponse.json({ error: '用戶不存在' }, { status: 404 });
  }
  
  const isPasswordValid = await bcrypt.compare(password, user.password);
  if (!isPasswordValid) {
    return NextResponse.json({ error: '密码错误' }, { status: 401 });
  }

  const res = NextResponse.json(
    { message: '登入成功', user: { id: user.id, username: user.username } },
    { status: 200 },
  );
  res.cookies.set('userId', user.id, {
    httpOnly: true,
    path: '/',
    sameSite: 'lax',
    // secure: true,
    maxAge: 60 * 60 * 24 * 7, // 7天
  });
  return res;
}